package util;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 自定义工具类
 * @author ljldn
 *
 */
public class MyUtils {
	/**
	 * 将ResultSet转换为JSONArray
	 * @param rs
	 * @return
	 * @throws SQLException 
	 */
	public static JSONArray ResultSetToJSONArray(ResultSet rs) throws SQLException{
		JSONArray array = new JSONArray();
		ResultSetMetaData meta = rs.getMetaData();
		int colNum = meta.getColumnCount();//列数
		while(rs.next()){
			JSONObject object = new JSONObject();
			for(int i =1;i <=colNum;i++){
				String field = meta.getColumnName(i);
				Object o = rs.getObject(i);
				object.put(field, o);
			}
			array.add(object);
		}
		return array;
	}
	/**
	 * 将JSONArray转换为复合返回格式的json字符串
	 * @param array
	 * @param total
	 * @return
	 */
	public static String getResultStr(JSONArray array,int total){
		if(total<=0){
			total = array.size();
		}
		String result = "{\"total\":\""+total+"\",\"rows\":"+array+"}";
		return result;
	}
	/**
	 * 将ResultSet 直接输出
	 * @param rs
	 * @param resp
	 * @param total
	 * @throws SQLException 
	 */
	public static void print(ResultSet rs,HttpServletResponse resp,int total) throws SQLException{
		JSONArray array = ResultSetToJSONArray(rs);
		String result = getResultStr(array,total);
		try {
			resp.getWriter().print(result);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
